<?php
/**
 * Created by PhpStorm.
 * 定时操作业务（用于liunx定时调用）
 * User: caicm
 * Date: 2017/5/24
 * Time: 15:56
 */

namespace SDXApi\Controller;


use SDXApi\Service\OrderDistributionTimeService;
use SDXApi\Service\UserBonusService;
use Think\Cache\Driver\Redis;
use Think\Controller;
use SDXApi\Service\WorkorderService;
use Think\Exception;

class TimingOperationController extends Controller {

    protected function _initialize() {
        set_time_limit(0);
        header("Access-Control-Allow-Origin: *");
    }

    /**
     * 自动关闭售后工单（客服回复后，用户7天内未追加，自动改为关闭）
     * 执行时间：每天凌晨3点调取
     * Created By caicm
     */
    public function close_workorder(){

        $workorder_service = new WorkorderService();
        $data = $workorder_service->close_workorder(7);
        if($data){
            returnApiSuccess($data);
        }else{
            returnApiError('没有要关闭的工单');
        }

    }

    /**
     * 订单超时处理
     * 每半小时处理
     * Created By caicm
     */
    public function order_overtime(){
        $over_mod = new OrderDistributionTimeService();
        $data = $over_mod->order_overtime(4);
        if($data){
            returnApiSuccess(array('res'=> '已处理：'.$data));
        }else{
            returnApiError('没有订单超时处理');
        }

    }

    /**
     * 更新红包队列
     * @author Min
     */
    public function update_bonus_queue()
    {
        $bonus_type_id = I('bonus_type_id');

        if (empty($bonus_type_id)) {
            returnApiError('参数有误');
        }

        $bonus_data = S('bonus_type_id_data_queue_'.$bonus_type_id);

        if (empty($bonus_data)) {
            return false;
        }

        $this->addBonusToqueue($bonus_type_id, 1);

    }

    /**
     * 添加红包id到redis队列
     * @author Min
     * @param null $bonus_type_id
     * @param int $is_update
     */
    public function addBonusToqueue($bonus_type_id = null, $is_update = 0)
    {
        if (empty($bonus_type_id)) {
            $bonus_type_id = I('bonus_type_id');
        }

        if (empty($bonus_type_id)) {
            returnApiError('参数有误');
        }

        $bonus_data = M("bonus_type")
            ->field('bouns_user_rank,has_effective_days,effective_days,android_version,ios_version,send_start_date,send_end_date')
            ->where(array("send_type" => 3,"type_id" => $bonus_type_id))
            ->find();

        $where = array("bonus_type_id" => $bonus_type_id, "user_id" =>0);
        if ($is_update == 1) {
            unset($where['user_id']);
        }

        $bonus_num = M('user_bonus')
            ->where( $where )
            ->count('bonus_id');

        $bonus_data['bonusCanGetNum'] = $bonus_num;

        S('bonus_type_id_data_queue_'.$bonus_type_id, $bonus_data);
        $_POST['store'] = 1;
        $user_bonus_service = new UserBonusService();

        if ($user_bonus_service->addBonusToqueue($bonus_type_id)) {
            //returnApiSuccess(null, 'ok');
            echo 'ok';
        } else {
            echo 'error';
            //returnApiError('error');
        }
    }

    /**
     * @author Min
     * @return bool
     */
    public function handelBonusQueue()
    {
        write_log('start', 'handelBonusQueue');
        $time = gmtime();

        $where = array(
            'send_type' => 3,
            'send_start_date' => array('between', ($time+60*5)."," .($time+60*30)),
        );

        $data = M('bonus_type')->field('type_id')->where($where)->select();

        write_log('ing_'.count($data).json_encode($data).'_'.M('bonus_type')->getLastSql(), 'handelBonusQueue');

        if (empty($data)) {
            return false;
        }

        foreach ($data as $key => $val) {
            $this->addBonusToqueue($val['type_id']);
        }

        write_log('end_'.count($data), 'handelBonusQueue');

    }

    /**
     * @author Min
     * @param $bonus_type_id
     * @param $bonus_data
     * @param $bonus_id
     * @return array
     * @throws Exception
     */
    public function handle_auto_bonus()
    {
        set_time_limit(720);
        try {
            $user_bonus_service = new UserBonusService();
            $queue = new Redis();
            $queue_key_wait = $user_bonus_service->getQueueKey_wait();
            while(1==1){
                while($u_bonus_id=$queue->lPop($queue_key_wait)){
                    list($bonus_type_id, $user_id, $bonus_id) = json_decode($u_bonus_id, true);

                    $bonus_data = S('bonus_type_id_data_queue_'.$bonus_type_id);

                    if ($bonus_data['has_effective_days'] == 1 && $bonus_data['effective_days'] > 0) {
                        $end_time = time() + ($bonus_data['effective_days'] - 1) * 24 * 3600;
                        $end_date = date('Y-m-d', $end_time) . " 23:59:59";
                        $deadline = local_strtotime($end_date); //转换成GMT格林威治时间戳
                    } else {
                        $deadline = 0;
                    }

                    $res = M("user_bonus")->where(array("bonus_id" => $bonus_id))->save(array('user_id' => $user_id, 'get_time' => gmtime(), 'deadline' => $deadline));

                    if ($res) {
                        S('add_user_bonus_type_id_' . $bonus_type_id . '_' . $user_id, $bonus_id);
                    }
                };
                sleep(0.2);
            };

        } catch (Exception $exception) {
            write_log($exception->getMessage(), 'handle_auto_bonus');
            header('Location: /index.php?s=/TimingOperation/handle_auto_bonus');
            exit;
        }

    }

}